<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>2-3</title>
    <style type="text/css">
        body{color:#999;font:12px/1.5 Tahoma;}
        #outer{width:500px;margin:0 auto;}
        #outer input{padding:3px;border:1px solid #ccc;font-family:inherit;width:220px;margin-right:10px;}
        .sum{font-size:30px;color:red;}
    </style>
</head>
<body>
<div id="outer">
    <label>
        <input value="1,2,3,4,5,6,7" type="text">
        <span>输入数字求和，数字之间用半角","号分隔</span>
    </label>
    <p><button>求和</button></p>
    <strong class="sum">120</strong>
</div>
<script type="text/javascript">

    var button = document.getElementsByTagName("button")[0];
    var input = document.getElementsByTagName("input")[0];
    var strong = document.getElementsByTagName("strong")[0];

    //限制用户只能输入数字和,号
    input.onkeyup = function(){
        this.value = this.value.replace(/[^(\d)|(,)]/,"");

    }

    button.onclick = function(){
        //将字符串折分成数组
        var tmp = input.value.split(",");
        var sum = 0;
        for(var i=0;i<tmp.length;i++){
            sum += parseInt(tmp[i]);
        }
        strong.innerHTML = sum;
    };

</script>
</body>
</html>